import { province, city, area } from "@/assets/data/address";
export default {
  methods: {
    // 根据id查询下一级的list：地区
    addressGetNextLevel(code) {
      let nextLevel = [];

      if (!code) {
        // 没有指定code，查省
        nextLevel = province;
      } else if (this.clickDeep === 0) {
        // 查省下的市，city匹配前两位
        nextLevel = city.filter(item => {
          return item.code.startsWith(code.substr(0, 2));
        });
      } else if (this.clickDeep === 1) {
        // 查市下的区，area匹配前4位
        nextLevel = area.filter(item => {
          return item.code.startsWith(code.substr(0, 4));
        });
      }

      // 空处理
      nextLevel = nextLevel || [];
      return nextLevel;
    },

    // 选中：address
    addressSelect(item) {
      // 地区选中需要遍历clickStack拿到省市区三个字段
      const clickStack = this.clickStack;
      // 赋值code与desc
      let provinceCode,
        provinceDesc,
        provincePostcode,
        cityCode,
        cityDesc,
        cityPostcode,
        areaCode,
        areaDesc,
        areaPostcode;
      // code
      provinceCode = clickStack[0].code;
      cityCode = clickStack[1].code;
      areaCode = item.code;
      // desc
      provinceDesc = clickStack[0].desc;
      cityDesc = clickStack[1].desc;
      areaDesc = item.desc;
      // postcode
      provincePostcode = clickStack[0].pc;
      cityPostcode = clickStack[1].pc;
      areaPostcode = item.pc;

      // emitItem
      const emitItem = {
        provinceCode, // 省code
        provinceDesc, // 省名称
        provincePostcode, // 省邮编
        cityCode, // 市code
        cityDesc, // 市名称
        cityPostcode, // 市邮编
        areaCode, // 区code
        areaDesc, // 区名称
        areaPostcode // 区邮编
      };
      this.$emit("select", emitItem);
    },

    // 回显地区
    reviewAddress() {
      // 省
      const findProvince = province.find(item => {
        return item.code === this.selectData.provinceCode;
      });
      // 市
      const findCity = city.find(item => {
        return item.code === this.selectData.cityCode;
      });
      // 区
      const findArea = area.find(item => {
        return item.code === this.selectData.areaCode;
      });
      if (findProvince && findCity && findArea) {
        // 找到对应数据，进行回显
        this.selectData.provinceDesc = findProvince.desc;
        this.selectData.provincePostcode = findProvince.pc;
        this.selectData.cityDesc = findCity.desc;
        this.selectData.cityPostcode = findCity.pc;
        this.selectData.areaDesc = findArea.desc;
        this.selectData.areaPostcode = findArea.pc;
      }
    },

    // 初始化地址
    initAddress() {
      // 如果当前selectData有值，则去做回显
      if (
        this.selectData.provinceCode &&
        this.selectData.cityCode &&
        this.selectData.areaCode
      ) {
        this.reviewAddress();
      }
    }
  }
};
